package com.atguigu.controller;

import com.atguigu.constant.Constant;
import com.atguigu.pojo.User;
import com.atguigu.service.UserService;
import com.atguigu.service.impl.UserServiceImpl;
import com.atguigu.utils.MD5Util;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

/**
 * @Author 马冰
 * @Date 2024/12/11 12:00
 * @version 1.0
 * @注释 用户登录界面操作
 */
@WebServlet("/user/login")
public class UserLoginController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取表单数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //2.创建业务层对象 调用方法根据用户名查询是否存在此用户
        UserService userService = new UserServiceImpl();
        User user = userService.findUserByName(username);
        //3.存在
        if (user != null) {
            //3.1对密码进行比较,看密码是否正确
            if (MD5Util.encrypt(password).equals(user.getPassword())) {
                //3.2密码正确 跳转到网站首页

                HttpSession session = req.getSession();
                session.setAttribute(Constant.SESSION_USER, user);


                resp.sendRedirect("/index.jsp");
            }else {
                //3.3密码不正确 跳转到密码不正确页面
                resp.sendRedirect("/loginPasswordError.html");
            }
        }else {
            //4.不存在,跳转到用户不存在页面
            resp.sendRedirect("/loginUsernameError.html");
        }

    }
}
